from django.shortcuts import render
from django.shortcuts import HttpResponse,render,redirect


# Create your views here.

#FBV装饰器
def islogin(func):
	def inner(request,*args,**kwargs):
		cookie_name = request.COOKIES.get('user_name')  # 获取当前cookie
		print(cookie_name)
		if not cookie_name:  #如果cookie不存在就跳转到登录页面
			err_msg = '请登录'
			return render(request, 'login.html', {'err_msg': err_msg})
			# return redirect('/tpl/login')
		else:  #否则，自动跳回原本的函数
			return func(request,*args,**kwargs)
	return inner

@islogin
def tpl(request):
	name = 'Beam test 模板继承'
	return render(request,'tpl.html',{'name':name})

#模拟一组数据库数据
LI = []
for i in range(500):
	LI.append('Beam-'+str(i))

@islogin
def userlist(request):
	from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger   #导入分页模块
	limit = 8  #设置每页的数量
	paginator = Paginator(LI,limit)  #实例化一个分页对象
	if request.method == 'POST':
		page = request.POST.get('page')
		print('POST:', page)
	else:
		page = request.GET.get('page')  # 获取页码
		print('GET:', page)
	try:
		userlist = paginator.page(page)  # 获取某页对应的记录
	except PageNotAnInteger:  # 如果页码不是个整数
		userlist = paginator.page(1)  # 取第一页的记录
	except EmptyPage:  # 如果页码太大，没有相应的记录
		userlist = paginator.page(paginator.num_pages)  # 取最后一页的记录

	return render(request,'userlist.html',{'userlist':userlist})





from tpl import models

def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    elif request.method == 'POST':
        u = request.POST.get('username')
        p = request.POST.get('password')
        obj = models.User.objects.filter(username = u,password = p).first()
        if obj:
	        res = redirect('/tpl/index')
	        res.set_cookie('user_name',u)  #设置一个cookie，cookie名叫user_name，将会写到浏览器里面的,关闭浏览器就会失效
	        return res
        else:
            err_msg = '该用户不存在'
            return render(request, 'login.html', {'err_msg': err_msg})
    else:
        return HttpResponse('404')

@islogin
def index(request):
	cookie_name = request.COOKIES.get('user_name')   #获取当前cookie
	return render(request,'index.html',{'username':cookie_name})


def cookie(request):
	cookies = request.COOKIES  #这是一个字典
	return HttpResponse(str(cookies))


from django.utils.decorators import method_decorator  #CBV模式使用装饰器需要用到这个
from django import views
# #全局使用装饰器方法二：
# #直接在class类上面加入：
# @method_decorator(islogin,name="dispatch")
class Order(views):

	# #全局使用装饰器方法一：
	# @method_decorator(islogin)
	# def dispatch(self,request,*args,**kwargs):
	# 	return super(Order,self).dispatch(request,*args,**kwargs)

	#  单独某个函数使用装饰器
	@method_decorator(islogin)
	def get(self,request):
		cookie_name = request.COOKIES.get('user_name')  # 获取当前cookie
		return render(request, 'index.html', {'username': cookie_name})

	def post(self,request):
		cookie_name = request.COOKIES.get('user_name')  # 获取当前cookie
		return render(request, 'index.html', {'username': cookie_name})













